/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.woxthebox.draglistview.sample.fraction;

import com.woxthebox.draglistview.basecomponent.BaseDependentLayout;
import com.woxthebox.draglistview.basecomponent.BaseDirectionalLayout;
import com.woxthebox.draglistview.minterface.MyObserver;
import com.woxthebox.draglistview.sample.ResourceTable;
import com.woxthebox.draglistview.sample.adapter.GridAdapter;
import com.woxthebox.draglistview.sample.adapter.ListAdapter;
import com.woxthebox.draglistview.sample.bean.ListBean;
import com.woxthebox.draglistview.sample.slice.MainAbilitySlice;
import com.woxthebox.draglistview.sample.untils.DataUntils;
import com.woxthebox.draglistview.utils.FinalStaticBean;
import com.woxthebox.draglistview.utils.ToastUtil;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.animation.AnimatorProperty;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.DirectionalLayoutManager;
import ohos.agp.components.DragInfo;
import ohos.agp.components.Image;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;
import ohos.agp.components.TableLayoutManager;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.hiviewdfx.HiLog;

import java.util.ArrayList;
import java.util.List;

/**
 * ListFractionAbility类
 *
 * @since 2021-04-21
 */
public class ListFractionAbility extends Fraction {
    private ListContainer listContainer;
    private ListAdapter mListAdapter;
    private List<ListBean> list = new ArrayList<>();
    private MainAbilitySlice slice;
    private BaseDependentLayout dependentLayout;
    private GridAdapter gridAdapter;
    private float mTouchDownY;
    private float mDragMoveY;
    private Display display;
    private Image image;
    private DirectionalLayout directionalLayout;
    private boolean isAnimator = false;
    private boolean isEnable = true;
    private MyObserver observer = new MyObserver() {
        @Override
        public void response(BaseDependentLayout component, int action) {
            int index = listContainer.getIndexForComponent(component);
            if (dependentLayout != null) {
                dependentLayout.reset();
            }
            if (action == FinalStaticBean.RIGHTMOVE) {
                list.remove(index);
                listContainer.getItemProvider().notifyDataSetItemRemoved(index);
            }
            if (component != dependentLayout) {
                if (dependentLayout != null) {
                    dependentLayout.setIsRed(false);
                }
                dependentLayout = component;
            }
        }
    };

    /**
     * ListFractionAbility构造
     *
     * @param slice
     */
    public ListFractionAbility(MainAbilitySlice slice) {
        this.slice = slice;
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        Component component = scatter.parse(ResourceTable.Layout_list_fraction_layout, container, false);
        display = DisplayManager.getInstance().getDefaultDisplay(slice).get();
        directionalLayout = (DirectionalLayout) component.findComponentById(ResourceTable.Id_borderlayout);
        listContainer = (ListContainer) component.findComponentById(ResourceTable.Id_list_fraction_listcontainer);
        image = (Image) component.findComponentById(ResourceTable.Id_list_fraction_img);
        directionalLayout.setContentPositionY(FinalStaticBean.NUM_0);
        listContainer.setDraggedListener(Component.DRAG_VERTICAL, new Component.DraggedListener() {
            @Override
            public void onDragDown(Component component, DragInfo dragInfo) {
                mTouchDownY = dragInfo.downPoint.getPointY();
            }

            @Override
            public void onDragStart(Component component, DragInfo dragInfo) {
            }

            @Override
            public void onDragUpdate(Component component, DragInfo dragInfo) {
                updateAnimator(dragInfo);
            }

            @Override
            public void onDragEnd(Component component, DragInfo dragInfo) {
                endAnimator();
            }

            @Override
            public void onDragCancel(Component component, DragInfo dragInfo) {
            }
        });

        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer mlistContainer, Component component, int i, long l) {
                ToastUtil.toast(slice,"Item clicked");
            }
        });
        return component;
    }

    private void endAnimator() {
        if (directionalLayout.getVisibility() == Component.VISIBLE && directionalLayout.getContentPositionY() > 0) {
            AnimatorProperty animatorProperty = image.createAnimatorProperty();
            animatorProperty.rotate(FinalStaticBean.NUM_1800).setDuration(FinalStaticBean.NUM_4000)
                    .setStateChangedListener(new Animator.StateChangedListener() {
                        @Override
                        public void onStart(Animator animator) {
                            isAnimator = true;
                        }

                        @Override
                        public void onStop(Animator animator) {
                        }

                        @Override
                        public void onCancel(Animator animator) {
                        }

                        @Override
                        public void onEnd(Animator animator) {
                            directionalLayout.setVisibility(Component.HIDE);
                            directionalLayout.setContentPositionY(0);
                            isAnimator = false;
                        }

                        @Override
                       public void onPause(Animator animator) {
                        }

                        @Override
                        public void onResume(Animator animator) {
                        }
                    }).start();
        } else if (directionalLayout.getContentPositionY() < 0) {
            directionalLayout.setVisibility(Component.HIDE);
        }
    }

    private void updateAnimator(DragInfo dragInfo) {
        float updatePointPointY = dragInfo.updatePoint.getPointY();
        if (listContainer.getFirstVisibleItemPosition() == 0) {
            if (updatePointPointY > mTouchDownY) {
                directionalLayout.setVisibility(Component.VISIBLE);
                float index = updatePointPointY - mTouchDownY;
                if (directionalLayout.getContentPositionY() < display.getAttributes().height / FinalStaticBean.NUM_7) {
                    directionalLayout.setContentPositionY(index);
                    image.setRotation(index);
                }
            }
            if (mTouchDownY > updatePointPointY && directionalLayout.getVisibility() == Component.VISIBLE) {
                directionalLayout.setVisibility(Component.VISIBLE);
                float index = updatePointPointY - mTouchDownY;
                directionalLayout.setContentPositionY(index);
                image.setRotation(index);
            }
        }
        if (isAnimator || directionalLayout.getVisibility() == Component.HIDE) {
            listContainer.scrollBy(0, (int) -dragInfo.yOffset);
        }
        mDragMoveY = updatePointPointY;
    }

    @Override
    protected void onStart(Intent intent) {
        HiLog.info(FinalStaticBean.DRAGLISTVIEW, "ListFraction onStart");
        if (list.size() > 0) {
            list.clear();
        }
        list.addAll(DataUntils.getlistData());
        if (mListAdapter == null) {
            mListAdapter = new ListAdapter(list, slice, FinalStaticBean.NOBORDER, observer);
            mListAdapter.setEnable(false);
        }
        listContainer.setItemProvider(mListAdapter);
        listContainer.setItemLongClickedListener(new ListContainer.ItemLongClickedListener() {
            @Override
            public boolean onItemLongClicked(ListContainer listContainer, Component component, int i, long l) {
                if (component instanceof BaseDirectionalLayout) {
                    ((BaseDirectionalLayout)component).onLongClicked(component);
                } else if (component instanceof BaseDependentLayout) {
                    ((BaseDependentLayout)component).onLongClicked(component);
                }
                return true;
            }
        });
    }

    /**
     * 可在外部AblitySlice中调用setLayoutType设置相应操作
     *
     * @param type
     */
    public void setLayoutType(int type) {
        if (type == FinalStaticBean.GRIDLAYOUTVERTICALTYPE) {
            TableLayoutManager tableLayoutManager = new TableLayoutManager();
            tableLayoutManager.setColumnCount(FinalStaticBean.NUM_4);
            tableLayoutManager.setOrientation(Component.HORIZONTAL);
            listContainer.setOrientation(Component.VERTICAL);
            listContainer.setLayoutManager(tableLayoutManager);
            gridAdapter = new GridAdapter(list,slice,FinalStaticBean.GRIDLAYOUTVERTICALTYPE);
            gridAdapter.setNeedBack(true);
            gridAdapter.setEnable(isEnable);
            listContainer.setItemProvider(gridAdapter);
        } else if (type == FinalStaticBean.GRIDLAYOUTHORIZONTALTYPE) {
            TableLayoutManager tableLayoutManager = new TableLayoutManager();
            tableLayoutManager.setRowCount(FinalStaticBean.NUM_4);
            tableLayoutManager.setOrientation(Component.VERTICAL);
            listContainer.setOrientation(Component.HORIZONTAL);
            listContainer.setLayoutManager(tableLayoutManager);
            gridAdapter = new GridAdapter(list,slice,FinalStaticBean.GRIDLAYOUTHORIZONTALTYPE);
            gridAdapter.setNeedBack(true);
            gridAdapter.setEnable(isEnable);
            listContainer.setItemProvider(gridAdapter);
        } else if (type == FinalStaticBean.LINEARLAYOUTTYPE) {
            DirectionalLayoutManager layoutManager = new DirectionalLayoutManager();
            layoutManager.setOrientation(Component.VERTICAL);
            listContainer.setLayoutManager(layoutManager);
            listContainer.setItemProvider(mListAdapter);
        } else if (type == FinalStaticBean.ENABLEDRAG && listContainer != null) {
            isEnable = true;
            listContainer.setLongClickable(true);
            if (listContainer.getItemProvider() instanceof ListAdapter) {
                mListAdapter.setEnable(isEnable);
                mListAdapter.notifyDataChanged();
            } else {
                gridAdapter.setEnable(isEnable);
                gridAdapter.notifyDataChanged();
            }
        } else if (type == FinalStaticBean.DISABLEDRAG && listContainer != null) {
            isEnable = false;
            listContainer.setLongClickable(false);
            if (listContainer.getItemProvider() instanceof ListAdapter) {
                mListAdapter.setEnable(isEnable);
                mListAdapter.notifyDataChanged();
            } else {
                gridAdapter.setEnable(isEnable);
                gridAdapter.notifyDataChanged();
            }
        }
    }
}